import random

from Spider.GetCode import Code
import logging

# 配置日志记录
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')


def generate_id_number(region_codes1, num_id_numbers1):
    id_numbers1 = []
    logging.info("调用身份证号生成算法")
    for _ in range(num_id_numbers1):
        region_code = random.choice(region_codes1)

        # 出生日期，随机生成一个在1998年到2004年之间的日期
        birth_year = random.randint(1998, 2004)
        birth_month = random.randint(1, 12)
        if birth_month == 2:
            birth_day = random.randint(1, 28)  # 简化处理，不考虑闰年
        else:
            birth_day = random.randint(1, 30)  # 假设每月最多30天
        birth_str = f"{birth_year:04d}{birth_month:02d}{birth_day:02d}"

        # 顺序码，随机生成3位数字
        sequence_code = str(random.randint(100, 999))

        # 拼接成前17位身份证号
        partial_id_number = region_code + birth_str + sequence_code

        # 计算校验码
        check_code = calculate_check_code(partial_id_number)

        # 最终身份证号码
        id_number = partial_id_number + check_code

        id_numbers1.append(str(id_number))
    logging.info("身份证号生成成功")
    return id_numbers1


def calculate_check_code(partial_id_number):
    # 加权因子
    weight_factors = [int(x) for x in '7 9 10 5 8 4 2 1 6 3 7 9 10 5 8 4 2'.split()]

    # 校验码对应值
    check_code_values = '10X98765432'

    # 计算加权和
    weighted_sum = sum(int(partial_id_number[i]) * weight_factors[i] for i in range(17))

    # 取模得到校验码对应的索引
    check_code_index = weighted_sum % 11

    # 返回校验码
    return check_code_values[check_code_index]

